const todoListCollection = 'todoList';

const getTodoList = (findData) => async (req, res) => {
    const todoList = await findData({ collection: todoListCollection, sort: { _id: -1 } });
    res.json({ message: '查询成功', code: 0, todoList });
}

const addTodo = (insertOne) => async (req, res) => {
    const { name } = req.payload;
    const todo = await insertOne(todoListCollection, { name });
    console.log(`添加代办事项: ${name}`, todo);
    if (todo.insertedId) {
        res.json({ message: "新增代办-请尽早提上日程", _id: todo.insertedId, notification: true });
    }
}

// notification:true 相应拦截器中 发现通知字段为true 则开启通知 不需要在callback中调用通知函数

const deleteTodo = (deleteOne) => async (req, res) => {
    const { id } = req.payload;
    const result = await deleteOne(todoListCollection, id);
    console.log(`删除todo id: ${id}`, result);
    if (result.acknowledged) {
        res.json({ message: "删除成功" })
    }
}

const updateTodo = (updateOne) => async (req, res) => {
    const { _id, result } = req.payload;
    const todo = await updateOne({
        collection: todoListCollection,
        _id,
        data: { result }
    });
    console.log(`啊哈哈哈 解决一件了 ${result}`, todo);
    if (todo.modifiedCount) {
        res.json({ message: "更改成功" });
    }
}

module.exports = {
    getTodoList, addTodo, deleteTodo, updateTodo
}